/*
 * @lc app=leetcode id=82 lang=cpp
 *
 * [82] Remove Duplicates from Sorted List II
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }

        ListNode *fakeNode = new ListNode(-1);
        fakeNode->next = head;
        ListNode *node = fakeNode;

        bool hasDuped = false;
        int val = node->next->val;
        while (node->next && node->next->next) {
            if (node->next->next->val == val) {
                ListNode *tmp = node->next->next;
                node->next->next = tmp->next;
                delete tmp;
                hasDuped = true;
            } else {
                if (hasDuped) {
                    hasDuped = false;
                    ListNode *tmp = node->next;
                    node->next = tmp->next;
                    delete tmp;
                } else {
                    node = node->next;
                }
                if (node->next)
                    val = node->next->val;
            }
        }

        if (hasDuped) {
            delete node->next;
            node->next = nullptr;
        }

        head = fakeNode->next;
        delete fakeNode;
        return head;
    }
};

